<template>
  <div class="page-container" style="height: 100vh; overflow: auto;">
    <!-- 顶部横幅（与会员中心相同样式） -->
    <div class="header-banner">
      <h2>积分商城</h2>
      <p>兑换精美商品，享受会员专属特权</p>
    </div>

    <el-card class="box-card">
      <!-- 积分展示（与会员中心完全相同） -->
      <div class="points-header">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="当前积分">
            <div class="points-display">
              <el-tag type="warning" class="points-tag">
                <i class="el-icon-coin"></i> {{ currentPoints }} 积分
              </el-tag>
              <el-button 
                type="text" 
                size="small" 
                @click="showPointsDetail"
                class="points-detail-btn">
                查看积分规则
              </el-button>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 商品兑换区 -->
      <div class="goods-section">
        <h3 class="section-title">可兑换商品</h3>
        <div class="goods-grid">
          <el-card 
            v-for="item in goodsList" 
            :key="item.id"
            shadow="hover"
            class="goods-card">
            <div class="goods-image">
              <img :src="item.image" :alt="item.name">
            </div>
            <div class="goods-info">
              <h4>{{ item.name }}</h4>
              <p class="goods-desc">{{ item.description }}</p>
              <div class="goods-action">
                <span class="points-required">
                  <i class="el-icon-coin"></i> {{ item.pointsRequired }}积分
                </span>
                <el-button
                  type="warning"
                  :disabled="currentPoints < item.pointsRequired"
                  @click="handleExchange(item.id)">
                  立即兑换
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 积分规则弹窗（复用会员中心代码） -->
    <el-dialog
      v-model="pointsDetailVisible"
      title="积分规则"
      width="500px">
      <div class="points-detail-content">
        <!-- 完全复用会员中心的积分规则内容 -->
        <div class="current-rate">
          您当前是<strong>{{ formatMembershipLevel(memberLevel) }}</strong>，
          每消费1元可获得<strong>{{ getPointsRate(memberLevel) }}积分</strong>
        </div>
        <div class="rules-title">积分规则:</div>
        <ul class="rules-list">
          <li>银米会员(1级)：1元=0积分</li>
          <li>金米会员(2级)：1元=1积分</li>
          <li>白金会员(3级)：1元=1.5积分</li>
          <li>钻石会员(4级)：1元=2积分</li>
          <li>至尊会员(5级)：1元=3积分</li>
          <li>积分可兑换余额</li>
          <li>每月1日清零上月积分</li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMembershipService,
  exchangePointsToBalance 
} from '@/api/user'
import { useRouter } from 'vue-router'

// 积分数据（与会员中心完全相同的获取方式）
const currentPoints = ref(0)
const memberLevel = ref(1)
const pointsDetailVisible = ref(false)


// 商品列表数据
const goodsList = ref([
  {
    id: 1,
    name: '5元余额',
    image: 'https://via.placeholder.com/300x200?text=Coupon',
    description: '立即到账',
    pointsRequired: 100
  },
  {
    id: 2,
    name: '10元余额',
    image: 'https://via.placeholder.com/300x200?text=Shipping',
    description: '立即到账',
    pointsRequired: 200
  },
  {
    id: 3,
    name: '20元余额',
    image: 'https://via.placeholder.com/300x200?text=Upgrade',
    description: '立即到账',
    pointsRequired: 400
  },
  {
    id: 4,
    name: '50元余额',
    image: 'https://via.placeholder.com/300x200?text=Upgrade',
    description: '立即到账',
    pointsRequired: 900
  },
  {
    id: 5,
    name: '100元余额',
    image: 'https://via.placeholder.com/300x200?text=Upgrade',
    description: '立即到账',
    pointsRequired: 1600
  },
  {
    id: 6,
    name: '500元余额',
    image: 'https://via.placeholder.com/300x200?text=Upgrade',
    description: '立即到账',
    pointsRequired: 6666
  }
])

// 获取会员数据（完全复制会员中心的方法）
const fetchMemberData = async () => {
  try {
    const res = await getMembershipService()
    if (res.data?.code === '200') {
      currentPoints.value = res.data.data?.points || 0
      memberLevel.value = res.data.data?.membershipLevel || 1
    }
  } catch (error) {
    ElMessage.error('积分数据加载失败')
    console.error('获取会员数据失败:', error)
  }
}

// 兑换商品
const handleExchange = async (goodsId) => {
  try {
    const goods = goodsList.value.find(item => item.id === goodsId)
    await ElMessageBox.confirm(`确认兑换 ${goods.name}?`, '提示')
    const userId = JSON.parse(localStorage.getItem('userInfo')).id
    console.log(parseInt(goods.name.replace('元余额', '')))
    const res = await exchangePointsToBalance({
      userId: userId,
      points: goods.pointsRequired,
      wallet: parseInt(goods.name.replace('元余额', ''))
    })
    ElMessage.success('兑换成功！')
      await fetchMemberData() // 重新获取用户数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`兑换失败: ${error.message}`)
      console.error('兑换错误详情:', error) // 打印详细错误
    }
  }
}

// 以下方法完全从会员中心复制
const showPointsDetail = () => {
  pointsDetailVisible.value = true
}

const formatMembershipLevel = (level) => {
  const map = { 
    1: '银米会员',
    2: '金米会员',
    3: '白金米会员',
    4: '钻石米会员',
    5: '至尊钻石米会员'
  }
  return map[level] || '普通用户'
}

const getPointsRate = (level) => {
  const rateMap = {
    1: 0,
    2: 1,
    3: 1.5,
    4: 2,
    5: 3
  }
  return rateMap[level] || 0
}

onMounted(() => {
  fetchMemberData() // 初始化获取数据
})
</script>

<style scoped>
/* 完全复用会员中心的样式 */
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  /* overflow: auto; */
  padding: 12px;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
}

.header-banner {
  text-align: center;
  padding: 16px 20px;
  background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
  color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 8px;
  }
  
  p {
    font-size: 14px;
    margin: 0;
    opacity: 0.9;
  }
}

.box-card {
  flex: 1;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.points-display {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .points-tag {
    border-radius: 12px;
    padding: 6px 12px;
    font-size: 14px;
    
    i {
      margin-right: 4px;
    }
  }
  
  .points-detail-btn {
    padding: 0;
    margin-left: 8px;
    color: var(--el-color-primary);
  }
}

.goods-section {
  margin-top: 20px;
  
  .section-title {
    font-size: 18px;
    font-weight: 500;
    color: var(--text-color);
    margin-bottom: 16px;
  }
  
  .goods-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
  }
  
  .goods-card {
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .goods-image {
      height: 160px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .goods-info {
      padding: 15px;
      
      h4 {
        margin: 10px 0 5px;
        font-size: 16px;
      }
      
      .goods-desc {
        color: #888;
        font-size: 13px;
        margin: 8px 0;
      }
      
      .goods-action {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .points-required {
          color: #e6a23c;
          font-weight: bold;
          
          i {
            margin-right: 3px;
          }
        }
      }
    }
  }
}
.goods-content {
  padding: 20px;
  text-align: center;
  
  h4 {
    font-size: 18px;
    color: #333;
    margin: 0 0 10px;
  }
  
  .goods-desc {
    color: #666;
    margin-bottom: 15px;
  }
}

/* 余额展示样式 */
:deep(.el-descriptions__body) {
  .el-tag {
    font-size: 16px;
    padding: 8px 12px;
    
    i {
      margin-right: 5px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .goods-grid {
    grid-template-columns: 1fr;
  }
  
  .points-display {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>